define(function (require) {
var zsApp = require('app');  
zsApp.controller( 'effectCtrl',['$rootScope', '$scope', '$http', '$state', '$timeout', 'cache', 'promptCache', 'selectCache', 'perSelectCache', function( $rootScope, $scope, $http, $state, $timeout, cache, promptCache, selectCache, perSelectCache ) {
	// 默认关闭弹窗
	// $(".modal-backdrop").remove();

	// pagination
	$rootScope.paginationConf = {
        currentPage    : 1,
        totalItems     : 10,
        itemsPerPage   : 10,
        pagesLength    : 15,
        perPageOptions : [10, 20, 30, 40, 50],
        onChange: function(){ 
        	var self = this,
        		treeReqVo = {
                    id          : cache.get('functionId')||0,
                    pageNumber  : self.currentPage,  
                    pageSize    : self.itemsPerPage,  
                };
			$http({
				url    : $scope.zsUrl+'digitalhome-boss/user/functions/getSublevelInfo',
				method : 'POST',
				data   : treeReqVo,
			}).success(function(res) {  console.log(res.result);

				if( res.result_code != '0000' ) {
                    $scope.isNoData = false;
                    return false;
                }
                    
                // 表格数据
                $scope.tabVal = res.result;
                // 遍历每条数据对应的ID
                angular.forEach(res.result, function(obj, i) {
                    $scope.dataID[i] = obj.functionId;
                });
                // 遍历每条数据对应的Name
                angular.forEach(res.result, function(obj, i) {
                    $scope.dataName[i] = obj.functionName;
                });
                // 总共有多少条数据
                self.totalItems = res.length;

			}).error(function(err) { 
				$scope.isNoData = false;
			});
        }
    };

    // reload table
    $scope.reloadPagination = function() {
        $scope.paginationConf.onChange();
    };

    // newlyAdded get function name
    $scope.newlyAdded = function() { 
        superior();
    };

    // newlyAdded: submit
    $scope.submitNewlyAdded = function() {

    	var newlyAddedData = { 
    		parentId        : cache.get('functionId'),
    		functionName	: $scope.newlyAdded_functionName,
    		functionCode	: $scope.newlyAdded_functionCode,
    		functionEName	: $scope.newlyAdded_functionEName,
    		pageUrl 		: $scope.newlyAdded_pageUrl,
    		functionType	: $scope.newlyAdded_functionType,
    		enable			: $scope.newlyAdded_enable,
    		description		: $scope.newlyAdded_description,
    	};

    	$http
    	({
    		url 	: $scope.zsUrl+'digitalhome-boss/user/functions/add',
    		method 	: 'POST',
    		data 	: newlyAddedData,

    	}).success(function(res) {

    		if( res.result_code != '0000' ) {
                promptCache.errorPrompt(res.message);
                return false;
            }

            promptCache.successPrompt(res.message);
            reloadTable();
            
    	}).error(function() {
    		promptCache.errorPrompt('新增失败！');
    		return false;
    	});
    };

    // details
    $scope.details = function(i) { 
    	superior();

    	$http({
    		url 	:  $scope.zsUrl+'digitalhome-boss/user/functions/getFunctionsInfo/'+$scope.dataID[i],
    		method 	: 'GET',

    	}).success(function(res) {

    		if( res.result_code != '0000' ) {
                return false;
            }

            $scope.details_functionName		= res.result.functionName;
    		$scope.details_functionCode		= res.result.functionCode;
    		$scope.details_functionEName	= res.result.functionEName;
    		$scope.details_pageUrl			= res.result.pageUrl;
    		$scope.details_functionType		= res.result.functionType;
    		$scope.details_enable			= res.result.enable;
    		$scope.details_description		= res.result.description;

    	}).error(function(err) {
    		promptCache.errorPrompt('请求失败！');
    		return false;
    	});
    };

    // edit: show data
    $scope.edit = function(i) { 

		superior();

		$scope.index = i;

    	$http({
    		url 	:  $scope.zsUrl+'digitalhome-boss/user/functions/getFunctionsInfo/'+$scope.dataID[i],
    		method 	: 'GET',

    	}).success(function(res) {

    		if( res.result_code != '0000' ) {
                return false;
            }

            $scope.edit_functionName	= res.result.functionName;
    		$scope.edit_functionCode	= res.result.functionCode;
    		$scope.edit_functionEName	= res.result.functionEName;
    		$scope.edit_pageUrl			= res.result.pageUrl;
    		$scope.edit_functionType	= res.result.functionType;
    		$scope.edit_enable			= res.result.enable;
    		$scope.edit_description		= res.result.description;

    		// function type select
    		$scope.editFunctionTypeSelect = [
    			{ 'id': 0, 'name': '功能点' },
    			{ 'id': 1, 'name': '功能页' },
    		];

    		// function enable select
    		$scope.editEnableSelect = [
    			{ 'id': 1, 'name': '启用' },
    			{ 'id': 0, 'name': '禁用' },
    		];

    	}).error(function(err) {
    		promptCache.errorPrompt('请求失败！');
    		return false;
    	});
    };

    // edit: submit data
    $scope.submitEdit = function() {

    	var editData = { 
    		functionId 		: $scope.dataID[$scope.index],
			functionName	: $scope.edit_functionName,
    		functionCode	: $scope.edit_functionCode,
    		functionEName	: $scope.edit_functionEName,
    		pageUrl 		: $scope.edit_pageUrl,
    		functionType	: $scope.edit_functionType,
    		enable			: $scope.edit_enable,
    		description		: $scope.edit_description,
    	};

    	$http
    	({
    		url 	: $scope.zsUrl+'digitalhome-boss/user/functions/modify',
    		method	: 'POST',
    		data 	: editData,

    	}).success(function(res) {

    		if( res.result_code != '0000' ) {
                promptCache.errorPrompt(res.message);
                return false;
            }

            promptCache.successPrompt(res.message);
            reloadTable();

    	}).error(function(err) {
			promptCache.errorPrompt('修改失败！');
			return false;
    	});
    };

    // delete enable disabled
    $scope.getDataID = function() {
        // data length
        var len = $scope.dataID.length;
        // param id
        var whichId = 'functionId';
        // param
        var deleteUrl = 'user/functions/deleteInfo';
        // enable disabled
        var isEnableUrl = 'user/functions/modifyStatus';

        // multiple selections 
        $scope.selectAll= function (bool, obj) {
            selectCache.selectAll(bool, $scope.dataID);
        };

        //  single or multiple selections 
        $scope.select= function (selectObj, bool) {   
            var selectId = selectObj.functionId;        
            selectCache.select(selectId, bool, len);    
        }; 

        // check
        $scope.check= function () {
            selectCache.check();
        };

        // delete
        $scope.delete= function () { 
            selectCache.delete(whichId, deleteUrl);
            reloadTable();
        };

        // enable
        $scope.enable= function () { 
            selectCache.isEnable(whichId, isEnableUrl, 1);
            reloadTable();
        };

        // disabled
        $scope.disabled= function () { 
            selectCache.isEnable(whichId, isEnableUrl, 0);
            reloadTable();
        };
    };

    // move
    $scope.move = function() {
    	promptCache.prompt('功能暂未开放！');
    };

    // superior
    function superior() {
        if( cache.get('functionName') ) {
            $scope.functionName = cache.get('functionName');
        }else {
            $scope.functionName = '最上级';
        }
    };
    // reload table
    function reloadTable() { 
        $timeout(function() {
            $scope.paginationConf.onChange();
            $scope.master = false;
        },1500);
    };

    // 所有复选框
    $scope.permission = function(i) {

        perSelectCache.init();

        $scope.isChecked = false;
        
        var fnId   = $scope.dataID[i],
            fnName = $scope.dataName[i],
            len    = 0;

        var whichFnId       = 'functionId',
            whichFnName     = 'functionName',
            whichPerId      = 'operationId',
            whichPerName    = 'operationName',
            whichUrl        = 'user/functions/modifyPermission';

        var operationId     = [],
            operationName   = [];

        // 初始化（默认值）
        var defaultUrl = 'user/functions/getRelationedList';
        perSelectCache.defSelect(fnId, defaultUrl);

        // 所有权限列表
        $http({

            url     : $scope.zsUrl+'digitalhome-boss/admin/operations/getPermissionList',
            method  : 'POST',
            data    : {
                pageNumber  : 1,
                pageSize    : 20,
            }

        }).success(function(res) {  

            console.log(res.result);

            // 数据
            $scope.permissionVal = res.result;

            len = $scope.permissionVal.length;

        }).error(function(res) {
            console.log(res);
        });



        // 默认选中部分权限列表
        var TreeReqVo = { 
            id          : fnId, 
            pageNumber  : 1,
            pageSize    : 20,
        };

        $http
        ({
            url     : $scope.zsUrl+'digitalhome-boss/user/functions/getRelationedList',
            method  : 'POST',
            data    : TreeReqVo,

        }).success(function(res) {

            var defSelectedId = [];
            var defSelectedName = [];

            angular.forEach(res.result, function(obj, i) {
                defSelectedId[i] = obj.operationId;
                defSelectedName[i] = obj.operationName;
            });

            $scope.isSelected = function(id, name) {

                // if( defSelectedId.indexOf(id) != -1 ) {
                //     perSelectCache.select(id, name, true, len);

                // }
                

                return defSelectedId.indexOf(id) != -1;
            };

        }).error(function(err) {
            console.log(err);
        });

        // 全选
        $scope.selectAll = function(perBool, permissionVal) {

            $scope.isChecked = true;
            
            // $scope.isSelected = function () {
            //     return false;
            // }

            

            angular.forEach(permissionVal, function(obj, i) {
                operationId[i]   = obj.operationId;
                operationName[i] = obj.operationName;
            });

            perSelectCache.selectAll(perBool, operationId, operationName);
        };



        // 单选（多选）
        $scope.select = function(val, sonBool, i) {

            console.log(sonBool);

            $scope.isChecked = false;            

            var operationId   = val.operationId;
            var operationName = val.operationName;

            // console.log();

            perSelectCache.select(operationId, operationName, sonBool, len);

        };

        // 提交关联的权限列表
        $scope.submitAssociated = function() {

            perSelectCache.isPermission(whichFnId, whichFnName, fnId, fnName, whichPerId, whichPerName, whichUrl);
            // 清空全选
            $scope.perBool = false;
        };

    };

    
    
}])
.directive('effectNewlyadded', function() {
	return {
		restrict	: 'E',
		templateUrl : 'user/effect/newlyAdded.html',
		replace		: true,	
	}
})
.directive('effectDelete', function() {
	return {
		restrict 	: 'E',
		templateUrl : 'user/effect/delete.html',
		replace		: true,	
	}
})
.directive('effectDetails', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'user/effect/details.html',
		replace		: true,	
	}
})
.directive('effectEdit', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'user/effect/edit.html',
		replace		: true,	
	}
})
.directive('effectTable', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'user/effect/table.html',
		replace		: true,	
	}
})
.directive('effectPermission', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'user/effect/permission.html',
		replace		: true,	
	}
})
});